//
//  DECXDeliveryViewController.m
//  DECXInStore
//
//  Created by 李坤 on 2018/9/7.
//  Copyright © 2018年 程强. All rights reserved.
//

#import "DECXDeliveryViewController.h"
#import "DECXDriversListViewController.h"
#import "DECXDriverObj.h"
#import "DECXDriverTableCell.h"
#import "DECXManager.h"
#import "DecimalDigitManager.h"
#import "DECXWarehouseChargeManager.h"
#import "DECXDeliveryListViewController.h"

@interface DECXDeliveryViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) DECXManager *manager;
@property (weak, nonatomic) IBOutlet UILabel *listNoLbl;
@property (weak, nonatomic) IBOutlet UILabel *stockLbl;
@property (weak, nonatomic) IBOutlet UITextField *deliveryCountLbl;
@property (weak, nonatomic) IBOutlet UIView *driverView;
@property (weak, nonatomic) IBOutlet UITableView *driverTable;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *driverViewHeight;
@property (strong, nonatomic) NSArray *selectedDrivers;
@property (strong, nonatomic) DecimalDigitManager *ciamalManager;
@property (weak, nonatomic) IBOutlet UIView *payBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backScrollBottom;
@property (strong, nonatomic) DECXWarehouseChargeManager *wManager;
@end

@implementation DECXDeliveryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DECXManager new];
    self.wManager = [DECXWarehouseChargeManager new];
    [self setupUI];
    self.ciamalManager = [DecimalDigitManager new];
    _ciamalManager.decimalDigit = 2;
    self.deliveryCountLbl.delegate = _ciamalManager;
    if ([DECXGlobal shareInstance].loginType.integerValue == 3) {
        [self setRightBarItem];
    }
}
- (void)setupUI
{
    self.listNoLbl.text = self.order.getlist_id;
    self.stockLbl.text = [NSString stringWithFormat:@"%@吨",self.order.weight_useable];
    self.driverView.hidden = YES;
    if ([DECXGlobal shareInstance].loginType.integerValue == 2) {
        self.payBackView.hidden = NO;
        self.backScrollBottom.constant = 60;
    }else if ([DECXGlobal shareInstance].loginType.integerValue == 3){
        self.payBackView.hidden = YES;
        self.backScrollBottom.constant = 0;
    }
}
- (void)setRightBarItem
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick)];
    self.navigationItem.rightBarButtonItem = item;
}
- (BOOL)checkInput
{
    if (self.deliveryCountLbl.text.length == 0) {
        ToastShowInWindow(@"请填写提货数量");
        return NO;
    }
    if ([self.deliveryCountLbl.text floatValue]>[self.order.weight_useable floatValue]) {
        ToastShowInWindow(@"可提货重量需小于仓库剩余重量");
        return NO;
    }
    if (self.selectedDrivers.count==0) {
        ToastShowInWindow(@"请添加提货司机");
        return NO;
    }
    return YES;
}
- (void)commitClick
{
    weak_Self(self);
    [self performBlock:^{
        [weakSelf deliveryProduct];
    } delay:0.5];
}
- (IBAction)choseDriverClick:(id)sender
{
    weak_Self(self);
    DECXDriversListViewController *vc = StoryBoardViewController(@"Main", @"DECXDriversListViewController");
    [self.navigationController pushViewController:vc animated:YES];
    [vc choseDriversHandler:^(NSArray *ary) {
        weakSelf.selectedDrivers = ary;
        [weakSelf.driverTable reloadData];
        weakSelf.driverViewHeight.constant = 44*ary.count+41;
        weakSelf.driverView.hidden = NO;
    }];
}
- (NSString *)getSelectedDriverIds
{
    __block NSString *ids = @"";
    [self.selectedDrivers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DECXDriverObj *driver = obj;
        ids = [ids stringByAppendingString:driver.xid];
        if (idx!=self.selectedDrivers.count-1) {
            ids = [ids stringByAppendingString:@","];
        }
    }];
    return ids;
}
- (void)deliveryProduct
{
    MyUser;
    weak_Self(self);
    NSString *depot_id;
    NSString *type;
    if ([DECXGlobal shareInstance].loginType.integerValue == 2) {
        depot_id = self.order.depot_id;
        type = @"2";
    }else{
        depot_id = user.depot_id;
        type = @"1";
    }
    [[self.manager deliveryProduct:self.order.list_id weight:self.deliveryCountLbl.text user_id:user.userid depot_id:depot_id driver:[self getSelectedDriverIds] type:type]subscribeNext:^(id x) {
        [weakSelf showMessageHUD:@"提货成功" delayHide:1.0];
        [weakSelf performBlock:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } delay:1.0];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.selectedDrivers.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"Driver";
    
    DECXDriverTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DECXDriverTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    DECXDriverObj *driver = self.selectedDrivers[indexPath.row];
    cell.name.text = driver.user_name;
    cell.carNo.text = driver.car_code;
    return cell;
}
- (IBAction)payButtonClick:(id)sender
{
    [self.deliveryCountLbl resignFirstResponder];
    if (![self checkInput]) {
        return;
    }
    [self payAlert];
}
#pragma mark --- 选择支付方式
- (void)payAlert
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"线上支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self createOnLinePayOrder];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"线下支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self commitClick];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark --- 线上支付订单
- (void)createOnLinePayOrder
{
    MyUser;
    weak_Self(self);
    [[self.wManager createPayOrderWithUid:user.userid orderID:self.order.list_id count:self.deliveryCountLbl.text driver:[self getSelectedDriverIds]]subscribeNext:^(id x) {
        DECXDeliveryListViewController *vc = StoryBoardViewController(@"Main", @"DECXDeliveryListViewController");
        [weakSelf.navigationController pushViewController:vc animated:YES];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [weakSelf showMessageHUD:msg delayHide:1.0];
    } completed:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
